#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "esp_system.h"
#include "esp_log.h"
#include "esp_err.h"
#include "esp_check.h"
#include "driver/gpio.h"
#include "driver/ledc.h"
#include "driver/adc.h"
#include "esp_adc_cal.h"
#include <inttypes.h>
#include "hardware.h"
#include "agriculture_ui.h"
#include "ui_status.h"

static const char *TAG = "AGRI_UI";

// LVGL对象句柄
static lv_obj_t *g_screen = NULL;
static lv_obj_t *g_main_container = NULL;   // 主容器
static lv_obj_t *g_page_single = NULL;      // 单页面

// 监测数据标签
static lv_obj_t *g_label_temp = NULL;
static lv_obj_t *g_label_humidity = NULL;
static lv_obj_t *g_label_light = NULL;
static lv_obj_t *g_label_soil = NULL;

// 控制页面元素
static lv_obj_t *g_switch_pump = NULL;
static lv_obj_t *g_switch_light = NULL;
static lv_obj_t *g_switch_fan = NULL;

// 系统信息标签
static lv_obj_t *g_label_auto_status = NULL;

// 全局数据
static agriculture_data_t g_agri_data = {
    .temperature = 25.0,
    .humidity = 50.0,
    .light_intensity = 800,
    .soil_moisture = 45.0,
    .pump_status = false,
    .fan_status = false,
    .fan_speed = 0,
    .light_status = false,
    .soil_threshold = 40.0,
    .temp_threshold = 30.0,
    .humidity_threshold = 80.0
};

// 颜色定义
#define COLOR_BACKGROUND lv_color_hex(0xFFFFFF)
#define COLOR_TEXT lv_color_hex(0x000000)
#define COLOR_STATUS_ONLINE lv_color_hex(0x00FF00)
#define COLOR_STATUS_OFFLINE lv_color_hex(0xFF0000)

// 初始化传感器
static esp_err_t sensor_init(void)
{
    adc1_config_width(ADC_WIDTH_BIT_12);
    adc1_config_channel_atten(ADC1_CHANNEL_7, ADC_ATTEN_DB_12); // 土壤湿度传感器 - GPIO35
    adc1_config_channel_atten(ADC1_CHANNEL_6, ADC_ATTEN_DB_12); // 光照传感器 - GPIO34
    
    gpio_config_t io_conf = {
        .pin_bit_mask = (1ULL << GPIO_NUM_23) | (1ULL << GPIO_NUM_22) | (1ULL << GPIO_NUM_26),
        .mode = GPIO_MODE_OUTPUT,
        .pull_up_en = GPIO_PULLUP_DISABLE,
        .pull_down_en = GPIO_PULLDOWN_DISABLE,
        .intr_type = GPIO_INTR_DISABLE
    };
    gpio_config(&io_conf);
    
    ledc_timer_config_t fan_timer = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .duty_resolution = LEDC_TIMER_8_BIT,
        .timer_num = LEDC_TIMER_0,
        .freq_hz = 1000,
        .clk_cfg = LEDC_AUTO_CLK
    };
    ledc_timer_config(&fan_timer);
    
    ledc_channel_config_t fan_channel = {
        .gpio_num = GPIO_NUM_22,
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .channel = LEDC_CHANNEL_0,
        .intr_type = LEDC_INTR_DISABLE,
        .timer_sel = LEDC_TIMER_0,
        .duty = 0,
        .hpoint = 0
    };
    ledc_channel_config(&fan_channel);
    
    ESP_LOGI(TAG, "Sensor init done");
    return ESP_OK;
}

// 读取传感器数据
static void read_sensor_data(void)
{
    int soil_raw = adc1_get_raw(ADC1_CHANNEL_7);
    g_agri_data.soil_moisture = (soil_raw / 4095.0 * 100.0);
    
    int light_raw = adc1_get_raw(ADC1_CHANNEL_6);
    g_agri_data.light_intensity = light_raw * 2;
    
    g_agri_data.temperature += ((float)rand() / RAND_MAX - 0.5) * 0.3;
    g_agri_data.humidity += ((float)rand() / RAND_MAX - 0.5) * 0.8;
    
    if (g_agri_data.temperature < 10) g_agri_data.temperature = 10;
    if (g_agri_data.temperature > 40) g_agri_data.temperature = 40;
    if (g_agri_data.humidity < 20) g_agri_data.humidity = 20;
    if (g_agri_data.humidity > 95) g_agri_data.humidity = 95;
}

// 更新设备状态
static void update_device_status(void)
{
    // 移除自动模式逻辑，保持手动控制
    
    gpio_set_level(GPIO_NUM_23, g_agri_data.pump_status);
    // 使用已配置的输出引脚控制补光灯，避免占用LCD复位引脚
    gpio_set_level(GPIO_NUM_26, g_agri_data.light_status);
    
    if (g_agri_data.fan_status) {
        uint8_t duty = (g_agri_data.fan_speed * 255) / 100;
        ledc_set_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0, duty);
        ledc_update_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0);
    } else {
        ledc_set_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0, 0);
        ledc_update_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0);
    }
}

// 开关事件回调函数
static void switch_event_cb(lv_event_t *e)
{
    lv_obj_t *target = lv_event_get_target(e);
    bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
    ESP_LOGI(TAG, "开关事件: obj=%p state=%d", (void*)target, (int)state);
    
    if (target == g_switch_pump) {
        ESP_LOGI(TAG, "水泵开关切换为: %s", state ? "ON" : "OFF");
        g_agri_data.pump_status = state;
    } else if (target == g_switch_light) {
        ESP_LOGI(TAG, "补光灯开关切换为: %s", state ? "ON" : "OFF");
        g_agri_data.light_status = state;
    } else if (target == g_switch_fan) {
        ESP_LOGI(TAG, "风扇开关切换为: %s", state ? "ON" : "OFF");
        g_agri_data.fan_status = state;
        g_agri_data.fan_speed = state ? 100 : 0;
    }
    
    update_device_status();
}

// 标签点击事件：切换对应的开关状态，并触发开关的值变化逻辑
static void label_click_toggle_cb(lv_event_t *e)
{
    lv_obj_t *sw = (lv_obj_t *)lv_event_get_user_data(e);
    if (!sw) return;
    ESP_LOGI(TAG, "标签点击: 目标开关=%p", (void*)sw);
    bool checked = lv_obj_has_state(sw, LV_STATE_CHECKED);
    if (checked) lv_obj_clear_state(sw, LV_STATE_CHECKED);
    else lv_obj_add_state(sw, LV_STATE_CHECKED);
    // 复用 switch_event_cb 的处理
    lv_obj_send_event(sw, LV_EVENT_VALUE_CHANGED, NULL);
}

// 创建单页面
static void create_single_page(void)
{
    ESP_LOGI(TAG, "创建单页面 - 步骤1: 创建页面容器");
    g_page_single = lv_obj_create(g_main_container);
    lv_obj_set_size(g_page_single, lv_obj_get_width(g_screen), lv_obj_get_height(g_screen));
    lv_obj_set_pos(g_page_single, 0, 0);
    lv_obj_set_style_bg_color(g_page_single, COLOR_BACKGROUND, 0);
    lv_obj_set_style_border_width(g_page_single, 0, 0);
    lv_obj_set_style_pad_all(g_page_single, 0, 0); // 清除所有边距
    lv_obj_clear_flag(g_page_single, LV_OBJ_FLAG_SCROLLABLE);

    ESP_LOGI(TAG, "创建单页面 - 步骤2: 创建状态栏");
    // 状态指示栏
    lv_obj_t *status_bar = lv_obj_create(g_page_single);
    lv_obj_set_size(status_bar, lv_obj_get_width(g_screen), 30);
    lv_obj_set_pos(status_bar, 0, 0);
    lv_obj_set_style_bg_color(status_bar, lv_color_hex(0x333333), 0);
    lv_obj_set_style_border_width(status_bar, 0, 0);
    lv_obj_set_style_pad_all(status_bar, 0, 0); // 清除所有边距
    // 使用符号状态栏显示 WiFi/BT 状态
    ui_status_init(status_bar);
    ui_status_set_wifi(false);
    ui_status_set_bt(false);
    
    ESP_LOGI(TAG, "创建单页面 - 步骤3: 创建自动模式标签");
    // 创建自动模式标签
    lv_obj_t *auto_label = lv_label_create(status_bar);
    lv_label_set_text(auto_label, "Auto:");
    lv_obj_set_style_text_color(auto_label, lv_color_hex(0xFFFFFF), 0);
    lv_obj_align(auto_label, LV_ALIGN_LEFT_MID, 5, 0);
    
    // 创建自动模式状态标签
    g_label_auto_status = lv_label_create(status_bar);
    lv_label_set_text(g_label_auto_status, "Off");
    lv_obj_set_style_text_color(g_label_auto_status, lv_color_hex(0xFFFFFF), 0);
    lv_obj_align_to(g_label_auto_status, auto_label, LV_ALIGN_OUT_RIGHT_MID, 5, 0);

    ESP_LOGI(TAG, "创建单页面 - 步骤4: 创建数据显示区域");
    // 数据显示区域 - 调整大小和位置以确保完整显示
    lv_obj_t *temp_area = lv_obj_create(g_page_single);
    lv_obj_set_size(temp_area, 150, 70);
    lv_obj_set_pos(temp_area, 5, 33);
    lv_obj_set_style_bg_color(temp_area, lv_color_hex(0x6BBEFF), 0);
    lv_obj_set_style_border_width(temp_area, 0, 0); // 移除边框
    lv_obj_set_style_pad_all(temp_area, 0, 0); // 清除所有边距
    
    lv_obj_t *humi_area = lv_obj_create(g_page_single);
    lv_obj_set_size(humi_area, 150, 70);
    lv_obj_set_pos(humi_area, 160, 33);
    lv_obj_set_style_bg_color(humi_area, lv_color_hex(0x99CCFF), 0);
    lv_obj_set_style_border_width(humi_area, 0, 0); // 移除边框
    lv_obj_set_style_pad_all(humi_area, 0, 0); // 清除所有边距
    
    lv_obj_t *light_area = lv_obj_create(g_page_single);
    lv_obj_set_size(light_area, 150, 70);
    lv_obj_set_pos(light_area, 5, 106);
    lv_obj_set_style_bg_color(light_area, lv_color_hex(0xFFE699), 0);
    lv_obj_set_style_border_width(light_area, 0, 0); // 移除边框
    lv_obj_set_style_pad_all(light_area, 0, 0); // 清除所有边距
    
    lv_obj_t *soil_area = lv_obj_create(g_page_single);
    lv_obj_set_size(soil_area, 150, 70);
    lv_obj_set_pos(soil_area, 160, 106);
    lv_obj_set_style_bg_color(soil_area, lv_color_hex(0x996633), 0);
    lv_obj_set_style_border_width(soil_area, 0, 0); // 移除边框
    lv_obj_set_style_pad_all(soil_area, 0, 0); // 清除所有边距

    ESP_LOGI(TAG, "创建单页面 - 步骤5: 创建设备控制区域");
    // 设备控制区域 - 调整大小和位置以适应屏幕，确保完全覆盖底部区域
    lv_obj_t *control_area = lv_obj_create(g_page_single);
    lv_obj_set_size(control_area, LCD_V_RES, 60); // 进一步增加高度确保覆盖底部
    lv_obj_align(control_area, LV_ALIGN_BOTTOM_MID, 0, 0); // 使用底部对齐而非固定位置
    lv_obj_set_style_bg_color(control_area, lv_color_hex(0x2D2D2D), 0);
    lv_obj_set_style_border_width(control_area, 0, 0); // 移除边框
    lv_obj_set_style_pad_all(control_area, 0, 0); // 设置边距

    // 横向排列的控制项
    int item_width = LCD_V_RES / 3;

    ESP_LOGI(TAG, "创建单页面 - 步骤6: 创建水泵控制");
    // 水泵控制 - 简化标签
    lv_obj_t *pump_label = lv_label_create(control_area);
    lv_label_set_text(pump_label, "pump");
    lv_obj_set_style_text_color(pump_label, lv_color_hex(0xFFFFFF), 0);
    lv_obj_align(pump_label, LV_ALIGN_LEFT_MID, item_width * 0, 0);
    lv_obj_add_flag(pump_label, LV_OBJ_FLAG_CLICKABLE);

    g_switch_pump = lv_switch_create(control_area);
    lv_obj_align(g_switch_pump, LV_ALIGN_LEFT_MID, item_width * 0 + 45, 0);
    lv_obj_set_width(g_switch_pump, 55); // 调整开关宽度
    lv_obj_add_state(g_switch_pump, g_agri_data.pump_status ? LV_STATE_CHECKED : 0);
    lv_obj_add_event_cb(g_switch_pump, switch_event_cb, LV_EVENT_VALUE_CHANGED, NULL);
    
    ESP_LOGI(TAG, "创建单页面 - 步骤6.1: 绑定水泵标签点击事件");
    lv_obj_add_event_cb(pump_label, label_click_toggle_cb, LV_EVENT_CLICKED, g_switch_pump);

    ESP_LOGI(TAG, "创建单页面 - 步骤7: 创建补光灯控制");
    // 补光灯控制 - 简化标签
    lv_obj_t *light_label = lv_label_create(control_area);
    lv_label_set_text(light_label, "light");
    lv_obj_set_style_text_color(light_label, lv_color_hex(0xFFFFFF), 0);
    lv_obj_align(light_label, LV_ALIGN_LEFT_MID, item_width * 1 + 5, 0);
    lv_obj_add_flag(light_label, LV_OBJ_FLAG_CLICKABLE);

    g_switch_light = lv_switch_create(control_area);
    lv_obj_align(g_switch_light, LV_ALIGN_LEFT_MID, item_width * 1 + 40, 0);
    lv_obj_set_width(g_switch_light, 55); // 调整开关宽度
    lv_obj_add_state(g_switch_light, g_agri_data.light_status ? LV_STATE_CHECKED : 0);
    lv_obj_add_event_cb(g_switch_light, switch_event_cb, LV_EVENT_VALUE_CHANGED, NULL);
    
    ESP_LOGI(TAG, "创建单页面 - 步骤7.1: 绑定补光灯标签点击事件");
    lv_obj_add_event_cb(light_label, label_click_toggle_cb, LV_EVENT_CLICKED, g_switch_light);

    ESP_LOGI(TAG, "创建单页面 - 步骤8: 创建通风扇控制");
    // 通风扇控制 - 简化标签
    lv_obj_t *fan_label = lv_label_create(control_area);
    lv_label_set_text(fan_label, "fan");
    lv_obj_set_style_text_color(fan_label, lv_color_hex(0xFFFFFF), 0);
    lv_obj_align(fan_label, LV_ALIGN_LEFT_MID, item_width * 2 + 10, 0);
    lv_obj_add_flag(fan_label, LV_OBJ_FLAG_CLICKABLE);

    g_switch_fan = lv_switch_create(control_area);
    lv_obj_align(g_switch_fan, LV_ALIGN_LEFT_MID, item_width * 2 + 35, 0);
    lv_obj_set_width(g_switch_fan, 55); // 调整开关宽度
    lv_obj_add_state(g_switch_fan, g_agri_data.fan_status ? LV_STATE_CHECKED : 0);
    lv_obj_add_event_cb(g_switch_fan, switch_event_cb, LV_EVENT_VALUE_CHANGED, NULL);
    
    ESP_LOGI(TAG, "创建单页面 - 步骤8.1: 绑定通风扇标签点击事件");
    lv_obj_add_event_cb(fan_label, label_click_toggle_cb, LV_EVENT_CLICKED, g_switch_fan);
    
    ESP_LOGI(TAG, "创建单页面 - 步骤9: 创建数据标签样式");
    // 数据标签
    static lv_style_t title_style;
    lv_style_init(&title_style);
    lv_style_set_text_font(&title_style, &lv_font_montserrat_14); // 设置合适的字体大小
    
    static lv_style_t value_style;
    lv_style_init(&value_style);
    lv_style_set_text_font(&value_style, &lv_font_montserrat_14); // 使用相同的字体以避免错误
    
    ESP_LOGI(TAG, "创建单页面 - 步骤10: 创建温度标签");
    // 温度标签
    lv_obj_t *temp_title = lv_label_create(temp_area);
    lv_label_set_text(temp_title, "TEMP");
    lv_obj_add_style(temp_title, &title_style, 0);
    lv_obj_set_style_text_color(temp_title, COLOR_TEXT, 0);
    lv_obj_align(temp_title, LV_ALIGN_TOP_MID, 0, 15);
    
    g_label_temp = lv_label_create(temp_area);
    lv_label_set_text(g_label_temp, "25.5°C");
    lv_obj_add_style(g_label_temp, &value_style, 0);
    lv_obj_set_style_text_color(g_label_temp, COLOR_TEXT, 0);
    lv_obj_align(g_label_temp, LV_ALIGN_CENTER, 0, 0);
    
    // 湿度标签
    lv_obj_t *humi_title = lv_label_create(humi_area);
    lv_label_set_text(humi_title, "HUM");
    lv_obj_add_style(humi_title, &title_style, 0);
    lv_obj_set_style_text_color(humi_title, COLOR_TEXT, 0);
    lv_obj_align(humi_title, LV_ALIGN_TOP_MID, 0, 15);
    
    g_label_humidity = lv_label_create(humi_area);
    lv_label_set_text(g_label_humidity, "60%");
    lv_obj_add_style(g_label_humidity, &value_style, 0);
    lv_obj_set_style_text_color(g_label_humidity, COLOR_TEXT, 0);
    lv_obj_align(g_label_humidity, LV_ALIGN_CENTER, 0, 0);
    
    // 光照标签
    lv_obj_t *light_title = lv_label_create(light_area);
    lv_label_set_text(light_title, "LIGHT");
    lv_obj_add_style(light_title, &title_style, 0);
    lv_obj_set_style_text_color(light_title, COLOR_TEXT, 0);
    lv_obj_align(light_title, LV_ALIGN_TOP_MID, 0, 15);
    
    g_label_light = lv_label_create(light_area);
    lv_label_set_text(g_label_light, "800Lux");
    lv_obj_add_style(g_label_light, &value_style, 0);
    lv_obj_set_style_text_color(g_label_light, COLOR_TEXT, 0);
    lv_obj_align(g_label_light, LV_ALIGN_CENTER, 0, 0);
    
    // 土壤湿度标签
    lv_obj_t *soil_title = lv_label_create(soil_area);
    lv_label_set_text(soil_title, "SOIL");
    lv_obj_add_style(soil_title, &title_style, 0);
    lv_obj_set_style_text_color(soil_title, COLOR_TEXT, 0);
    lv_obj_align(soil_title, LV_ALIGN_TOP_MID, 0, 15);
    
    g_label_soil = lv_label_create(soil_area);
    lv_label_set_text(g_label_soil, "45%");
    lv_obj_add_style(g_label_soil, &value_style, 0);
    lv_obj_set_style_text_color(g_label_soil, COLOR_TEXT, 0);
    lv_obj_align(g_label_soil, LV_ALIGN_CENTER, 0, 0);
}

// 更新UI显示
static void update_ui_display(void)
{
    char buffer[32];
    
    // 更新环境数据
    if (g_label_temp) {
        sprintf(buffer, "%.1f°C", g_agri_data.temperature);
        lv_label_set_text(g_label_temp, buffer);
    }
    
    if (g_label_humidity) {
        sprintf(buffer, "%.1f%%", g_agri_data.humidity);
        lv_label_set_text(g_label_humidity, buffer);
    }
    
    if (g_label_light) {
        sprintf(buffer, "%dLux", g_agri_data.light_intensity);
        lv_label_set_text(g_label_light, buffer);
    }
    
    if (g_label_soil) {
        sprintf(buffer, "%.1f%%", g_agri_data.soil_moisture);
        lv_label_set_text(g_label_soil, buffer);
    }
    
    // 更新设备控制
    
    if (g_switch_pump) {
        if (g_agri_data.pump_status) lv_obj_add_state(g_switch_pump, LV_STATE_CHECKED);
        else lv_obj_clear_state(g_switch_pump, LV_STATE_CHECKED);
    }
    
    if (g_switch_light) {
        if (g_agri_data.light_status) lv_obj_add_state(g_switch_light, LV_STATE_CHECKED);
        else lv_obj_clear_state(g_switch_light, LV_STATE_CHECKED);
    }
    
    if (g_switch_fan) {
        if (g_agri_data.fan_status) lv_obj_add_state(g_switch_fan, LV_STATE_CHECKED);
        else lv_obj_clear_state(g_switch_fan, LV_STATE_CHECKED);
    }
    
    // 更新系统信息（模拟 WiFi/BT 状态切换）
    {
        static bool wifi_connected = false;
        static bool bt_connected = false;
        static int sys_update_count = 0;
        sys_update_count++;
        if (sys_update_count % 100 == 0) {
            wifi_connected = !wifi_connected;
        }
        if (sys_update_count % 150 == 0) {
            bt_connected = !bt_connected;
        }
        ui_status_set_wifi(wifi_connected);
        ui_status_set_bt(bt_connected);
    }
}

// 创建UI
void create_agriculture_ui(void)
{
    ESP_LOGI(TAG, "开始创建农业监测UI - 步骤1: 传感器初始化");
    sensor_init();
    ESP_LOGI(TAG, "开始创建农业监测UI - 步骤2: 获取屏幕对象");
    g_screen = lv_scr_act();
    if (!g_screen) {
        ESP_LOGE(TAG, "获取屏幕对象失败!");
        return;
    }
    ESP_LOGI(TAG, "开始创建农业监测UI - 步骤3: 设置背景色");
    lv_obj_set_style_bg_color(g_screen, COLOR_BACKGROUND, 0);
    
    ESP_LOGI(TAG, "开始创建农业监测UI - 步骤4: 创建主容器");
    g_main_container = lv_obj_create(g_screen);
    if (!g_main_container) {
        ESP_LOGE(TAG, "创建主容器失败!");
        return;
    }
    ESP_LOGI(TAG, "开始创建农业监测UI - 步骤5: 配置主容器");
    lv_obj_set_size(g_main_container, LCD_V_RES, LCD_H_RES);
    lv_obj_set_pos(g_main_container, 0, 0);
    lv_obj_set_style_bg_color(g_main_container, COLOR_BACKGROUND, 0);
    lv_obj_set_style_border_width(g_main_container, 0, 0);
    lv_obj_set_style_pad_all(g_main_container, 0, 0); // 清除所有边距
    lv_obj_clear_flag(g_main_container, LV_OBJ_FLAG_SCROLLABLE);
    
    ESP_LOGI(TAG, "开始创建农业监测UI - 步骤6: 创建单页面");
    create_single_page();
    
    ESP_LOGI(TAG, "农业监测UI创建完成!");
}

// 更新UI
void update_agriculture_ui(void)
{
    static int update_count = 0;
    update_count++;
    
    if (update_count % 15 == 0) {
        read_sensor_data();
        update_device_status();
    }
    
    if (update_count % 3 == 0) {
        update_ui_display();
        taskYIELD();
    }
}

// 获取数据
agriculture_data_t get_agriculture_data(void)
{
    return g_agri_data;
}

// 设置数据
void set_agriculture_data(agriculture_data_t *data)
{
    if (data) {
        memcpy(&g_agri_data, data, sizeof(agriculture_data_t));
    }
}